<template>
    <van-nav-bar title="商品详情" left-text="" @click-right="showShare = true" left-arrow @click-left="goBack">
        <template #right>
            <van-icon name="ellipsis" size="18" />
        </template>
    </van-nav-bar>

    <van-swipe :autoplay="3000" lazy-render>
        <van-swipe-item v-for="item in info.thumbs_list" :key="item">
            <img :src="item" />
        </van-swipe-item>
    </van-swipe>

    <div class="detailbox">
        <h4>{{ info.name }}</h4>
        <div class="price" style="color: rgb(238, 10, 36); font-size: 22px;"><em>单独购买￥</em>{{ info.price }} |
            <em>拼团价格￥</em> {{ info.buy }}<em style="float: right; color: rgb(183, 183, 191);">库存 {{ info.stock }} 件</em>
        </div>
    </div>
    <div class="allkbox"></div>

    <div class="info_choice">
        <!-- Sku 商品规格 -->
        <div class="commodity" @click="SkuShow = true">
            <div class="opt">
                <div class="title wanl-gray">
                    选择
                </div>
                <div class="option">
                    <div class="selected">
                        <div>
                            <span>尺码</span>
                            <span>颜色</span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="wanl-gray" onclick="location.href = './sku.html' ">
                <img src="/assets/images/go.png">
            </div>
        </div>
        <!-- 服务 -->
        <div class="commodity" @click="agreement = true">
            <div class="opt">
                <div class="title wanl-gray">
                    服务
                </div>
                <div class="option">
                    <div class="selected">
                        <div>
                            <span>7天无理由退款</span>
                            <span>·</span>
                            <span>24小时内发货</span>
                            <span>·</span>
                            <span>假一赔十</span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="wanl-gray" onclick="location.href = './server.html' ">
                <img src="/assets/images/go.png">
            </div>
        </div>
    </div>
    <div class="clear"></div>
    <div class="allkbox"></div>
    <div class="clear"></div>
    <div class="detailbox_2">
        <van-tabs type="card" color="#ee0a24">
            <van-tab title="产品参数">
                <!-- 产品参数 -->
                <p v-html="info.content"></p>
            </van-tab>
            <van-tab title="商品评价">
                <!-- 商品评价 -->
                <div class="rate">
                    <div class="rate-header">
                        <div class="rate-score">
                            <h4>评分平均数</h4>
                            <strong>{{avgrate}}</strong>
                        </div>
                        <van-rate v-model="avgrate" readonly allow-half />
                    </div>
                    <div class="rate-content">
                        <div>
                            <div class="review-box" v-for="item in rate" :key="item.id">
                                <div class="review-item">
                                    <div class="from-whom">
                                        <div class="avatar">
                                            <img :src="item.business.avatar_text" alt="" />
                                        </div>
                                        <div class="name">{{ item.business.nickname }}</div>
                                    </div>
                                    <div class="review-details">
                                        <div class="content">{{ item.comment }}</div>
                                        <div>
                                            <span name="thumbs" label="" v-for="(thumb, index) in item.thumbs_list" :key="index">
                                                <van-image
                                                    :style="{ margin: '6px' }"
                                                    width="80"
                                                    height="80"
                                                    :src="thumb"
                                                />
                                            </span>
                                        </div>
                                        <div class="time">{{item.comtime_text}}</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div>
                            <!-- <div class="rate-empty">该商品还没有人写评价呢</div> -->
                        </div>
                    </div>
                </div>
            </van-tab>
        </van-tabs>
    </div>
    <div class="clear"></div>
    <div class="h54"></div>

    <!-- 协议内容 -->
    <van-action-sheet v-model:show="agreement" title="协议条款">
        <div class="ProductTip">
            三、我们如何使用信息 <br />
            四、我们如何共享信息<br />
            五、我们如何转让信息<br />
            六、我们如何公开披露信息<br />
            七、一般储存期限<br />
            八、我们如何确保您的信息安全<br />
            九、您能做什么<br />
            十、我们如何处理未成年人的个人信息<br />
            十一、您的个人信息的存储地点<br />
            十二、本隐私权政策不适用的范围<br />
            十三、本隐私权政策如何更新<br />
            十四、联系我们<br />
        </div>
    </van-action-sheet>

    <!-- 商品SKU -->
    <van-sku v-model="SkuShow" ref="SkuRef" stepper-title="购买数量" :sku="sku" :goods="goods" :goods-id="proid"
        :properties="properties" @buy-clicked="buy" @add-cart="addCart">
        <!-- 自定义 sku actions -->
        <template #sku-actions="props">
            <div class="van-sku-actions">
                <van-button square size="large" type="warning" @click="props.skuEventBus.emit('sku:addCart')">
                    加入购物车
                </van-button>
                <!-- 直接触发 sku 内部事件，通过内部事件执行 onBuyClicked 回调 -->
                <van-button square size="large" type="danger" @click="props.skuEventBus.emit('sku:buy')">
                    单独购买
                </van-button>
                <van-button square size="large" type="danger" @click="teamJoin">
                    参与拼团
                </van-button>
                <van-button square size="large" type="danger" @click="teamAdd">
                    发起拼团
                </van-button>
            </div>
        </template>
    </van-sku>

    <!--底部操作按扭 -->
    <van-action-bar>
        <van-action-bar-icon icon="chat-o" text="客服" @click="toCS" />
        <van-action-bar-icon icon="cart-o" text="购物车" :badge="info.cart_count" @click="toCartPages" />
        <!-- <van-action-bar-icon :icon= 'info.collection_active == false ? "shop-o" : "shop"' 
        :color="info.collection_active == false ? '' : '#ee0a24'"
        :text="info.collection_active == false ? '未收藏':'已收藏'" @click="toCollect"/> -->
        <van-action-bar-icon icon= "shop-o" text="未收藏" @click="toCollect" v-if="!info.collection_active" />
        <van-action-bar-icon icon="shop" color="#ee0a24" text="已收藏" @click="toCollect" v-else />
        <van-action-bar-button type="danger" text="立即购买" @click="SkuShow = true" />
    </van-action-bar>

    <!-- 分享面板 -->
    <van-share-sheet v-model:show="showShare" title="立即分享给好友" :options="sharelist" />

</template>
<script setup>
import VanSku from 'vant-sku';
import 'vant-sku/dist/index.css'
import { showNotify } from 'vant';
import { computed } from 'vue';
const { proxy } = getCurrentInstance()
const goBack = () => { proxy.$router.go(-1) }
const LoginUser = reactive(proxy.$cookies.get('LoginUser') ? proxy.$cookies.get('LoginUser') : {})
const showShare = ref(false);
const rate = ref([]);
const sharelist = [
    [
        { name: '微信', icon: 'wechat' },
        { name: '朋友圈', icon: 'wechat-moments' },
        { name: '微博', icon: 'weibo' },
        { name: 'QQ', icon: 'qq' },
    ],
    [
        { name: '复制链接', icon: 'link' },
        { name: '分享海报', icon: 'poster' },
        { name: '二维码', icon: 'qrcode' },
        { name: '小程序码', icon: 'weapp-qrcode' },
    ],
];
const proid = proxy.$route.query.proid ? proxy.$route.query.proid : 0;
const info = ref({})
const agreement = ref(false)

// 商品SKU
const SkuRef = ref(null)
const SkuShow = ref(false)
const goods = ref({})
const sku = ref({})
const properties = ref([])

onBeforeMount(() => {
    getProductInfoData()
    getRateInfoData()
})

const getRateInfoData = async () => {
    let rateresult = await Api.orderRateInfoData({
        busid: LoginUser.id,
        orderproid: proid
    });

    if (rateresult.code == 1) {
        rate.value = rateresult.data
    }
}
//尽量不要同名
const getProductInfoData = async () => {
    let result = await Api.productInfo({
        proid: proid,
        busid: LoginUser.id ? LoginUser.id : 0
    });
    if (result.code == 1) {
        let ProductData = result.data.info
        let SkuData = result.data.sku
        let PropertiesData = result.data.properties

        sku.value = SkuData
        properties.value = Object.values(PropertiesData)
        info.value = ProductData
        goods.value = {
            picture: ProductData.thumbs_text
        }
    }
}

const avgrate = computed(() => {
    const rates = rate.value.map( item => item.rate)
    
    // 检查是否有 rate 值
    if (rates.length === 0) {
        return 0; // 如果没有 rate 值，返回 0 或其他默认值
    }

    // 计算总和
    const sum = rates.reduce((acc, current) => acc + current, 0);
    console.log(sum)
    // 计算平均值
    const average = (sum / rates.length).toFixed(2);

    return Number(average);
})
const teamJoin = () => {
    if (JSON.stringify(LoginUser) == "{}") {
        success({
            message: '未登陆，请先去登陆',
            onClose: () => {
                proxy.$router.push('/business/login')
            }
        });
        return false;
    }

    // 通过 ref 可以获取到 Sku 实例并调用实例方法
    let skuData = SkuRef.value.getSkuData();

    //购买数量 
    let selectedNum = skuData.selectedNum;

    if (selectedNum <= 0) {
        error('数量不能为小于0');
        return false;
    }

    //判断是否有选择规格
    if (properties.value.length > 0 && !skuData.selectedSkuComb) {
        showNotify({ type: 'danger', message: '还有未选择的商品规格' });
        return false;
    }
    SkuShow.value = false
    let relationids = []

    // 有商品属性
    if (properties.value.length > 0) {
        let properties = skuData.selectedSkuComb.properties
        properties.forEach((item) => {
            if (item.v) {
                var id = item.v[0] ? item.v[0].id : 0;
                relationids.push({
                    id: id,
                    name: item.v[0].name ?? '',
                    price: item.v[0].price
                })
            }
        })
    }
    // 存储属性数据
    proxy.$cookies.set("relationids", JSON.stringify(relationids));

    proxy.$router.push({
        path: '/team/join',
        query: {
            proid: proid,
            nums: selectedNum
        }
    })
}

const teamAdd = () => {
    if (JSON.stringify(LoginUser) == "{}") {
        success({
            message: '未登陆，请先去登陆',
            onClose: () => {
                proxy.$router.push('/business/login')
            }
        });
        return false;
    }

    // 通过 ref 可以获取到 Sku 实例并调用实例方法
    let skuData = SkuRef.value.getSkuData();

    //购买数量 
    let selectedNum = skuData.selectedNum;

    if (selectedNum <= 0) {
        error('数量不能为小于0');
        return false;
    }
    
    //判断是否有选择规格
    if (properties.value.length > 0 && !skuData.selectedSkuComb) {
        showNotify({ type: 'danger', message: '还有未选择的商品规格' });
        return false;
    }
    SkuShow.value = false
    let relationids = []

    // 有商品属性
    if (properties.value.length > 0) {
        let properties = skuData.selectedSkuComb.properties
        properties.forEach((item) => {
            if (item.v) {
                var id = item.v[0] ? item.v[0].id : 0;
                relationids.push({
                    id: id,
                    name: item.v[0].name ?? '',
                    price: item.v[0].price
                })
            }
        })
    }

    // 存储属性数据
    proxy.$cookies.set("relationids", JSON.stringify(relationids));

    proxy.$router.push({
        path: '/team/add',
        query: {
            proid: proid,
            nums: selectedNum
        }
    })
}

const buy = async(skuData) => {
    if (JSON.stringify(LoginUser) == "{}") {
        success({
            message: '未登陆，请先去登陆',
            onClose: () => {
                proxy.$router.push('/business/login')
            }
        });

        return false;
    }

    if (properties.value.length > 0) {
        if(skuData.selectedSkuComb == null){
            showNotify({ type: 'danger', message: '还有未选择的商品规格' });
            return false;
        }
    }
    SkuShow.value = false;

    let selectedNum = skuData.selectedNum;

    if (selectedNum <= 0) {
        error('数量不能为小于0');
        return false;
    }

    let attrs = []

    let total = Number(info.value.price)*100

    // 有商品属性
    if (properties.value.length > 0) {
        let properties = skuData.selectedSkuComb.properties   
        properties.forEach((item) => {
            if (item.v) {
                attrs.push(item.v[0].id)
                total += item.v[0].price
            }
        })
    }
    proxy.$router.push({
        path: '/product/soleconfirm',
        query:{
            proid: proid,
            nums: selectedNum,
            attrs: attrs,
            attrstotal:total / 100
        }
    })
}



const addCart = async (skuData) => {
    if (properties.value.length > 0) {
        if(skuData.selectedSkuComb == null){
            showNotify({ type: 'danger', message: '还有未选择的商品规格' });
            return false;
        }
    }
    SkuShow.value = false;

    if (JSON.stringify(LoginUser) == "{}") {
        success({
            message: '未登陆，请先去登陆',
            onClose: () => {
                proxy.$router.push('/business/login')
            }
        });

        return false;
    }

    let selectedNum = skuData.selectedNum;

    if (selectedNum <= 0) {
        error('数量不能为小于0');
        return false;
    }

    let attrs = []
    
    // 有商品属性
    if (properties.value.length > 0) {
        let properties = skuData.selectedSkuComb.properties
        
        properties.forEach((item) => {
            if (item.v) {
                attrs.push(item.v[0].id)
            }
        })
    }

    let data = {
        busid: LoginUser.id,
        proid: proid,
        nums: selectedNum,
        attrs: attrs.toString()
    }

    let result = await Api.cartAdd(data);
    if (result.code == 1) {
        success({
            message: result.msg,
        });
    } else {
        error(result.msg);
    }

}

const toCartPages = () =>{
    proxy.$router.push('/product/cart')
}

const toCS = () =>{
    proxy.$router.push('/product/cs')
}
const toCollect = async () => {
    let collect = await Api.productCollect({
        proid:proid,
        busid:LoginUser.id
    })
    if (collect.code == 1 ){
        showNotify({ type: 'success', message: collect.msg });
        getProductInfoData()
    }
    else{
        showNotify({ type: 'danger', message: collect.msg });
        getProductInfoData()
    }
}
</script>
<style>
.van-share-sheet__options {
    justify-content: center;
}

.van-tabs__nav--card {
    margin: 0;
}
</style>